package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.enums.MediaEnum;
import com.heima.common.minio.service.MinIOService;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.dto.WmMaterialDto;
import com.heima.media.entity.WmMaterial;
import com.heima.media.mapper.WmMaterialMapper;
import com.heima.media.service.IWmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2021-12-25
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {


    @Autowired
    private MinIOService minIOService;


    /**
     * 上传媒体素材图片
     * @param file
     * @return
     */
    @Override
    public ResponseResult upload(MultipartFile file) {

        //0.先判断是否携带了token令牌
        User user = UserThreadLocalUtil.get();

        if (user == null) {
            //说明当前不是登陆状态
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //1.调用minio服务保存带minio中
        String fileUrl = minIOService.upload(file);

        //2.将素材文件进行保存
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(user.getUserId());
        wmMaterial.setUrl(fileUrl);
        wmMaterial.setType(MediaEnum.MEDIA_MATERIAL_TYPE_IMG.getVal());
        wmMaterial.setIsCollection(false);

        this.save(wmMaterial);

        //3.将素材对象返回
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 分页查询素材列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listByCollection(WmMaterialDto dto) {

        //1.先判断是否携带token
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.已经登陆，就进行根据userId进行分页查询
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmMaterial::getUserId, user.getUserId());

        //判断收藏状态是否存在
        if (dto.getIsCollection() != null) {
            queryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }

        //设置排序
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        //3.进行分页查询
        Page<WmMaterial> page = this.page(new Page<>(dto.getPage(), dto.getSize()), queryWrapper);

        return new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
    }
}
